/**
 * 
 */
package instant.mail;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
/**
 * @author qiangli
 * 
 */
public final class ContactUtils {
	public static void addList(Context ctx, String name, int star, String[] emails) {
		ContactAdapter ca = ContactAdapter.getAdapter();
		ca.addList(ctx, name, star, emails);
		//
		ContactListAdapter.notifyChange();
	}

	public static void saveAsContact(Context ctx, String name, int star, String[] emails) {
		ContactAdapter ca = ContactAdapter.getAdapter();
		ca.saveAsContact(ctx, name, star, emails);
		//
		ContactListAdapter.notifyChange();
	}

	public static void loadMailLists(Context ctx, List<String> lists) {
		ContactAdapter ca = ContactAdapter.getAdapter();
		lists.clear();
		//
		HashSet<String> set = new HashSet<String>();
		ca.loadListNames(ctx, set);
		lists.addAll(set);
		//
		Collections.sort(lists);
	}
	
	public static void loadAddresses(Context ctx, List<EmailAddress> addresses) {
		ContactAdapter ca = ContactAdapter.getAdapter();
		addresses.clear();
		//
		HashSet<EmailAddress> set = new HashSet<EmailAddress>();
		ca.loadEmailAddresses(ctx, set);
		addresses.addAll(set);
		//
		sort(addresses);
	}

	private static void sort(List<EmailAddress> addresses) {
		Comparator<EmailAddress> cp = new Comparator<EmailAddress>() {
			public int compare(EmailAddress a1, EmailAddress a2) {
				int c = a1.name.compareTo(a2.name);
				if (c == 0) {
					c = a1.address.compareTo(a2.address);
				}
				return c;
			}
		};
		Collections.sort(addresses, cp);
	}

	/**
	 * 
	 * @param ctx
	 * @param name
	 * @return sorted list of email addresses
	 */
	public static String[] getEmail(Context ctx, String name) {
		ContactAdapter ca = ContactAdapter.getAdapter();
		String[] emails = ca.getEmails(ctx, name);
		if (emails == null) {
			return new String[0];
		}
		Arrays.sort(emails); //
		return emails;
	}
	
	public static void loadContacts(Context ctx, List<EmailContact> contacts) {
		ContactAdapter ca = ContactAdapter.getAdapter();
		contacts.clear();
		HashSet<EmailContact> set = new HashSet<EmailContact>();
		//
		ca.loadEmailContacts(ctx, set );
		//
		contacts.addAll(set);
	}

	/**
	 * 
	 * @param context
	 * @param name
	 * @return
	 */
	public static long getId(Context ctx, String name) {
		ContactAdapter ca = ContactAdapter.getAdapter();
		return ca.getId(ctx, name);
	}
	
	public static void addEmail(Context ctx, long id, String[] emails) {
		ContactAdapter ca = ContactAdapter.getAdapter();
		ca.addEmail(ctx, id, emails);
		//
		ContactListAdapter.notifyChange();
	}

	public static boolean hasEmail(Context ctx, String email) {
		ContactAdapter ca = ContactAdapter.getAdapter();
		return ca.hasEmail(ctx, email);
	}

	public static Bitmap loadPhoto(Context ctx, long id, int res) {
		ContactAdapter ca = ContactAdapter.getAdapter();
		return ca.loadPhoto(ctx, id, res);
	}

	public static void toggleStar(Context ctx, EmailContact ec, int star) {
		long gid =  ec.id;
		if (gid >= -1) {
			return; //TODO not a list, not supported now
		}
		ContactAdapter ca = ContactAdapter.getAdapter();
		//
		ca.starList(ctx, gid, star);
		//
		ec.starred = star;
		ContactListAdapter.notifyChange();
	}

	public static void remove(Context ctx, EmailContact ec) {
		long gid =  ec.id;
		if (gid >= -1) {
			return; //not a list, not supported now
		}
		ContactAdapter ca = ContactAdapter.getAdapter();
		ca.removeList(ctx, gid);
		//
		ContactListAdapter.notifyChange();
	}
}

// junk yard

//public static void loadContacts(Context context, List<EmailContact> contacts) {
//	contacts.clear();
//	//
//	Uri uri = Contacts.ContactMethods.CONTENT_URI;
//	String[] proj = new String[] { ContactMethods.PERSON_ID,
//			PeopleColumns.DISPLAY_NAME, PeopleColumns.NAME,
//			PeopleColumns.STARRED, PeopleColumns.LAST_TIME_CONTACTED,
//			PeopleColumns.TIMES_CONTACTED, ContactMethodsColumns.KIND,
//			ContactMethodsColumns.TYPE, ContactMethodsColumns.ISPRIMARY,
//			ContactMethodsColumns.DATA };
//	String by = PeopleColumns.DISPLAY_NAME + " ASC, "
//			+ ContactMethodsColumns.DATA + " ASC ";
//	String sel = ContactMethodsColumns.KIND + " in (1, 3)"; // email and im
//
//	Cursor c = null;
//	c = context.getContentResolver().query(uri, proj, sel, null, by);
//	//
//	if (!c.moveToFirst()) {
//		return;
//	}
//	//
//	int colId = c.getColumnIndex(ContactMethods.PERSON_ID);
//	int colName = c.getColumnIndex(PeopleColumns.DISPLAY_NAME);
//	int colStar = c.getColumnIndex(PeopleColumns.STARRED);
//	int colEmail = c.getColumnIndex(ContactMethodsColumns.DATA);
//	int colLastTime = c.getColumnIndex(PeopleColumns.LAST_TIME_CONTACTED);
//	int colTimes = c.getColumnIndex(PeopleColumns.TIMES_CONTACTED);
//	String prev = "";
//	EmailContact ec = null;
//	ArrayList<String> el = new ArrayList<String>();
//	do {
//		String n = c.getString(colName);
//		if (n.equals(prev)) {
//			String s = c.getString(colEmail);
//			//
//			if (!el.contains(s)) {
//				el.add(s);
//			}
//		} else {
//			if (ec != null) {
//				ec.emails = el.toArray(new String[0]);
//				contacts.add(ec);
//			}
//			//
//			ec = new EmailContact();
//			el.clear();
//			prev = n;
//			//
//			ec.id = c.getLong(colId);
//			ec.name = n;
//			ec.starred = c.getInt(colStar);
//			ec.lastTime = c.getLong(colLastTime);
//			ec.times = c.getInt(colTimes);
//			//
//			String s = c.getString(colEmail);
//			if (!el.contains(s)) {
//				el.add(s);
//			}
//		}
//	} while (c.moveToNext());
//	if (ec != null) {
//		ec.emails = el.toArray(new String[0]);
//		contacts.add(ec);
//	}
//}

//public static String findContactId(Context context, String name) {
//	String[] proj = new String[] { People._ID, PeopleColumns.DISPLAY_NAME, };
//	Cursor c = context.getContentResolver().query(People.CONTENT_URI, proj,
//			PeopleColumns.DISPLAY_NAME + " = ?", new String[] { name },
//			null);
//	if (!c.moveToFirst()) {
//		return null;
//	}
//	// return the first one found
//	int idCol = c.getColumnIndex(People._ID);
//	String id = c.getString(idCol);
//	return id;
//}


//public static void loadAddresses(Context context,
//List<InternetAddress> addresses) {
//addresses.clear();
////
//Uri uri = Contacts.ContactMethods.CONTENT_URI;
//String[] proj = new String[] { PeopleColumns.DISPLAY_NAME,
//	ContactMethodsColumns.KIND, ContactMethodsColumns.DATA };
//String sel = ContactMethodsColumns.KIND + " in (1, 3)"; // email and im
//
//Cursor c = null;
//c = context.getContentResolver().query(uri, proj, sel, null, null);
////
//if (!c.moveToFirst()) {
//return;
//}
////
//int colName = c.getColumnIndex(PeopleColumns.DISPLAY_NAME);
//int colEmail = c.getColumnIndex(ContactMethodsColumns.DATA);
////
//Set<InternetAddress> al = new HashSet<InternetAddress>();
//do {
//String a = c.getString(colEmail);
//String n = c.getString(colName);
//try {
//	al.add(new InternetAddress(a, n));
//} catch (Exception e) {
//	// e.printStackTrace();
//}
//} while (c.moveToNext());
////
//addresses.addAll(al);
//
//}


//public InputStream openPhoto(long contactId) {
//Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
//Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
//Cursor cursor = getContentResolver().query(photoUri,
//     new String[] {Contacts.Photo.PHOTO}, null, null, null);
//if (cursor == null) {
//    return null;
//}
//try {
//    if (cursor.moveToFirst()) {
//        byte[] data = cursor.getBlob(0);
//        if (data != null) {
//            return new ByteArrayInputStream(data);
//        }
//    }
//} finally {
//    cursor.close();
//}
//return null;
//}

//private static Drawable loadPhoto(Context context, long cid) {
//BitmapFactory.Options opt = null;
//Bitmap bm = loadContactPhoto(context, cid, opt);
//return new BitmapDrawable(bm);
//}
//
//private static Bitmap loadContactPhoto(Context context, long contactId,
//	BitmapFactory.Options options) {
//Cursor cursor = null;
//Bitmap bm = null;
//try {
//	Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
//			contactId);
//	Uri photoUri = Uri.withAppendedPath(contactUri,
//			Contacts.Photos.CONTENT_DIRECTORY);
//	cursor = context.getContentResolver().query(photoUri,
//			new String[] { Contacts.Photos.DATA }, null, null, null);
//	if (cursor != null && cursor.moveToFirst()) {
//		bm = loadContactPhoto(cursor, 0, options);
//	}
//} finally {
//	if (cursor != null) {
//		cursor.close();
//	}
//}
//return bm;
//}
//
//private static Bitmap loadContactPhoto(Cursor cursor,
//	int bitmapColumnIndex, BitmapFactory.Options options) {
//if (cursor == null) {
//	return null;
//}
//
//byte[] data = cursor.getBlob(bitmapColumnIndex);
//return BitmapFactory.decodeByteArray(data, 0, data.length, options);
//}
//
//private static Bitmap loadDefaultPhoto(Context context, int res,
//	BitmapFactory.Options options) {
//if (res == 0) {
//	return null;
//}
//return BitmapFactory.decodeResource(context.getResources(), res,
//		options);
//}
